package com.pw.gmall.realtime.app.dwm;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONAware;
import com.alibaba.fastjson.JSONObject;
import com.pw.gmall.realtime.app.BaseApp;
import com.pw.gmall.realtime.common.Constant;
import com.pw.gmall.realtime.utils.KafkaUtils;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternSelectFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.PatternTimeoutFunction;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.util.List;
import java.util.Map;

/**
 * @Author: linux_future
 * @since: 2022/3/19
 **/
public class DwmUserJumpDetailAppV2 extends BaseApp {
    public static void main(String[] args) {
        new DwmUserJumpDetailAppV2().init(2004,1,"DwmUserJumpDetailAppV2","DwmUserJumpDetailAppV2", Constant.TOPIC_DWD_PAGE_LOG);
    }

    @Override
    protected void handler(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
       /* stream =
            env.fromElements(
                "{\"common\":{\"mid\":\"101\"},\"page\":{\"page_id\":\"home\"},\"ts\":10000} ",
                "{\"common\":{\"mid\":\"101\"},\"page\":{\"page_id\":\"home\"},\"ts\":11000} ",
                "{\"common\":{\"mid\":\"101\"},\"page\":{\"page_id\":\"home\"},\"ts\":12000} ",
                "{\"common\":{\"mid\":\"102\"},\"page\":{\"page_id\":\"home\"},\"ts\":10000}",
                "{\"common\":{\"mid\":\"102\"},\"page\":{\"page_id\":\"good_list\",\"last_page_id\":" +
                    "\"home\"},\"ts\":16000} ",
                "{\"common\":{\"mid\":\"102\"},\"page\":{\"page_id\":\"good_list\",\"last_page_id\":" +
                    "\"detail\"},\"ts\":50000} "
            );*/

        //水印
        WatermarkStrategy<JSONObject> wms = WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                .withTimestampAssigner((obj, ts) -> obj.getLong("ts"));


        //解析, 添加水印  按照mid分组
        KeyedStream<JSONObject, String> keyedStream = stream
                .map(JSON::parseObject)
                .assignTimestampsAndWatermarks(wms)
                .keyBy(obj -> obj.getJSONObject("common").getString("mid"));


        // 1. 定义模式
        Pattern<JSONObject, JSONObject> pattern = Pattern
                .<JSONObject>begin("entry1")
                .where(new SimpleCondition<JSONObject>() {
                    @Override
                    public boolean filter(JSONObject value) throws Exception {
                        // 入口
                        String lastPageId = value.getJSONObject("page").getString("last_page_id");
                        return lastPageId == null || lastPageId.length() == 0;
                    }
                })
                .next("entry2")
                .where(new SimpleCondition<JSONObject>() {
                    @Override
                    public boolean filter(JSONObject value) throws Exception {
                        String lastPageId = value.getJSONObject("page").getString("last_page_id");
                        return lastPageId == null || lastPageId.length() == 0;
                    }
                })
                .within(Time.seconds(5));

        // 2. 把模式作用到流上, 得到一个模式流
        PatternStream<JSONObject> ps = CEP.pattern(keyedStream, pattern);
        // 3. 从模式流中获取匹配到的数据, 或者超时的数据
        OutputTag<JSONObject> outputTagJump = new OutputTag<JSONObject>("jump") {};
        SingleOutputStreamOperator<JSONObject> mainStream = ps.select(outputTagJump,
                new PatternTimeoutFunction<JSONObject, JSONObject>() {
                    @Override
                    public JSONObject timeout(Map<String, List<JSONObject>> map,
                                              long timeoutTimestamp) throws Exception {
                        // 如果来了一个入口, 第二个入口在规定时间没有, 则第一个入口是跳出
                        return map.get("entry1").get(0);
                    }
                },
                new PatternSelectFunction<JSONObject, JSONObject>() {
                    @Override
                    public JSONObject select(Map<String, List<JSONObject>> map) throws Exception {
                        // 如果两个都是入口, 匹配模式, 第一个入口就是跳出
                        return map.get("entry1").get(0);
                    }

                }
        );

        //mainStream.getSideOutput(outputTagJump).print("超时数据：");
       // mainStream.print("主流数据：");
        mainStream.getSideOutput(outputTagJump).union(mainStream)
                .map(JSONAware::toJSONString)
                .addSink(KafkaUtils.getKafkaSink(Constant.TOPIC_DWM_UJ));

    }
}
